<?php
defined( '_VALID_MOS' ) or die('<script>window.location.href="http://www.kinifurniture.com";</script>');

// ------
// Database connection class.
// ------

class GenericDatabaseClass extends DB_MYSQL
{
	
	var $Host     = "localhost";
	var $User     = "root";
	var $Password = "";
	var $Database = "kinifurn_kini";
//	var $Host     = "localhost";
//	var $User     = "root";
//	var $Password = "";
//	var $Database = "kinifurniture";


}

// --------------------------------------------
// Global functions - all prepended with GSL_
// --------------------------------------------

// Function:		GSL_CheckSessionParameters
// Version:			1.0
// Modified:		15/01/2004
// Purpose:			Given a session id, pulls out certain fields from the database to return to the calling include file.
// Input:			$sid - session id
// Output:			List of requested parameters, separated by colons.  If the session id is bad, expired or in any other
//				way failes, this will just be a list of colons.
// Requirements:	The database handler $dbh must be instantiated in the calling function.
// Comments:		None.


function insertData($table,$column,$val){
	
	echo $query = " insert into $table ($column) values($val)";
 		if($this->dbh->query($query))
 			$message=mysql_error();			
 		else	
 			$message=mysql_error();				

	return $message;		
}//End of the function

function GSL_CheckSessionParameters($sid) {

	global $dbh;

	$sql = "select S.UserId,U.username,U.level from user_sessions S, users U where (S.session_code='$sid' and S.active='Y') and U.UserId = S.UserId";
	$dbh->query($sql);
	$dbh->next_record();
	$uid	= $dbh->f('UserId');
	$uname	= $dbh->f('username');
	$ulevel	= $dbh->f('level');

	return "$uid:$uname:$ulevel";
}

// Function:		GSL_ConvertMysqlDate
// Version:			1.0// Modified:		13/04/2004

// Purpose:			Converts MySQL format dates into those more acceptable to humans.
//					Handles both date ("Y-m-d") and datetime ("Y-m-d H:i:s") types.
//					Will convert to "d/m/Y" or "d/m/Y@H:i:s" respectively, except that the slashes dividing the date, the
//					colons dividing the time and the @ sign dividing each of them are configurable - these are just default.
// Input:			$mysql_date - the date to convert in one of the MySQL formats
//					$date_delim - date delimiter ** OPTIONAL ** defaults to "/"
//					$time_delim - time delimiter ** OPTIONAL ** defaults to ":"
//					$date_time_delim - date/time delimiter ** OPTIONAL ** defaults to "@"
// Output:			$date - human readable date
// Requirements:	None.
// Comments:		None.

function GSL_ConvertMysqlDate($mysql_date,$date_delim="/",$time_delim=":",$date_time_delim=" @ ") {

	$return = "";

	if(preg_match("/\s/",$mysql_date)) list($date,$time) = split(" ",$mysql_date);
	else { $date = $mysql_date; $time = ""; }

	list($Y,$m,$d) = split("-",$date);
	$date = $d.$date_delim.$m.$date_delim.$Y;

	if($time) {
		list($H,$i,$s) = split(":",$time);
		$time = $H.$time_delim.$i;
		$return = $date.$date_time_delim.$time;
	}
	else $return = $date;

	return $return;
}

// Function:		GSL_ParseHTML
// Version:			1.3
// Modified:		20/12/2003
// Purpose:			Open template file & parses it.  Appends to the end of the current HTML, which is also passed in
//					and then replaces any DATA_* values within the HTML with the equivalent $*, returning the lot.
//					For example, DATA_myvar becomes $myvar.  This can then be eval'd to replace $myvar with the contents
//					of that variable.
// Input:			$currentHTML = html to be appended to
//					$filename - name of the file containing html to append to $currentHTML
//					$skin (in the format "skin\d\d") - if not included, then skin directory for html is not used
// Output:			$newHTML - parsed html
// Requirements:	None.
// Comments:		None.



function GSL_ParseHTML($currentHTML,$filename,$skin="") {

	if($skin)	$filename = "./.html/$skin/$filename";
	else		$filename = "./.html/$filename";

	
	echo $newHTML = $currentHTML;

	$file = @fopen("$filename", "r") or die("Could not open template file $filename");
	$newHTML .= fread($file, filesize($filename));
	fclose($file);

	$newHTML = eregi_replace("\"", "\\\"", $newHTML);
	$newHTML = eregi_replace("DATA_", "$", $newHTML);

	return $newHTML;
}

// Function:		GSL_ParseText
// Version:			1.2
// Modified:		17/08/2003
// Purpose:			Parses HTML given as a parameter - rather than working on a file, as the previous function does.
//					Replaces any DATA_* values within the HTML with the equivalent $*, returning the lot.
//					For example, DATA_myvar becomes $myvar.  This can then be eval'd to replace $myvar with the contents
//					of that variable.
// Input:			$currentHTML - html to be parsed
// Output:			$newHTML - parsed html
// Requirements:	None.
// Comments:		None.

function GSL_ParseText($currentHTML) {

	$newHTML = $currentHTML;
	$newHTML = eregi_replace("\"", "\\\"", $newHTML);
	$newHTML = eregi_replace("DATA_", "$", $newHTML);

	return $newHTML;
}

// Function:		GSL_PseudoRandomPassword
// Version:			1.0
// Modified:		07/04/2003
// Purpose:			Creates a pseudo-random password, good enough for most non-secure applications.
// Input:			$length - length of the password to generate (4 character min, default 8)
// Output:			$pass - the plain-text password
// Requirements:	None.
// Comments:		This function is not suitable for the generation of truely random passwords in
//					systems which require a high-level of security.

function GSL_PseudoRandomPassword($length="8") {

	if($length < 4) $length = 8;
	$pass = "";
	$all=explode(" ", 
	"a b c d e f g h i j k l m n o p q r s t u v w x y z ".
	"A B C D E F G H I J K L M N O P Q R S T U V W X Y Z ".
	"- _ % # 0 1 2 3 4 5 6 7 8 9"); 
	for($i=0;$i<$length;$i++) { 
			srand((double)microtime()*1000000); 
			$randy=rand(0, 65); 
			$pass.=$all[$randy]; 
	}
	return $pass;
}

// Function:		GSL_GenericDD
// Version:			1.0
// Modified:		15/10/2003
// Purpose:			Creates a generic drop down list based on an SQL statement which pulls out a key (usually the row index) and a single value
//					(usually the textual value) from the mySQL DB.  Note, this function creates the "<option value=x>yyy</option>" rows, not
//					the surrounding "<select>...</select>" structure.
// Input:			$sql - SQL query to generate the output
//					$selected - the item which should be marked as selected (key rather than value) ** OPTIONAL **
// Output:			$my_dd - the drop down list
// Requirements:	The database handler $dbh must be instantiated in the calling function.
// Comments:		None.

function GSL_GenericDD($sql,$selected="",$default_text="") {

		$dbh = new GenericDatabaseClass;
		$my_dd = "";

		// Munge incoming SQL to use generic terms mykey & myvalue.
		$sql = preg_replace("/^select (\w+),(.+) from/","select $1 as id, $2 as name from",$sql);

		$dbh->query($sql);
		while($dbh->next_record()) {
			$key	= $dbh->f('id');
			$value	= $dbh->f('name');
			$my_dd .= "<option value='$key'>$value</option>\n";
		}

		if($selected)			$my_dd = preg_replace("/'$selected'>/"," '$selected' selected>",$my_dd);
		elseif($default_text)	$my_dd = "<option value=''>$default_text</option>\n$my_dd";

		// Return the DD
		return $my_dd;
}

// Function:		GSL_SendXLS
// Version:			1.3
// Modified:		15/10/2003
// Purpose:			Set up headers to allow sending of an XLS (csv) file to the desktop.
//					May include a title row, which defines the column headers.
// Input:			$filename - filename to save the XLS as
//					$sql - SQL query to generate the output
//					$show_title_row - show the field names as the first row (1=yes 0=no)
//					$field_name_array - an array to map raw field names to display names
// Output:			Nothing.
// Requirements:	The database handler $dbh must be instantiated in the calling function.
//					Processes using this function should terminate after use.
// Comments:		Some processes sourced from PHPmyAdmin, modified by stewb.

function GSL_SendXLS($filename,$sql,$show_title_row,$field_name_array) {

	// Use global dbh.
	global $dbh;
	
	$ext		= "csv";
	$mime_type	= "text/x-csv";

	// Send headers
	header('Content-Type: ' . $mime_type);

	// lem9 & loic1: IE need specific headers
	if(USR_BROWSER_AGENT == 'IE') {
		header('Content-Disposition: inline; filename="' . $filename . '.' . $ext . '"');
		header('Pragma: public');
	}
	else header('Content-Disposition: attachment; filename="' . $filename . '.' . $ext . '"');

	$dbh->query($sql);

	// XLS title row?
	if($show_title_row) {
		$content = "";
		$myfields = $dbh->field_names();
		while(list($key,$val) = each($myfields)) {
			if($field_name_array[$val]) $content .= "$field_name_array[$val],";
			else $content .= "$val,";
		}
		$content = preg_replace("/,$/","",$content);
		$content .= "\r\n";
	}

	// XLS content rows
	while($row = $dbh->next_raw_record()) {
		$content_tmp = "";
		while(list($key,$val) = each($row)) {
			$val = preg_replace("/\n/","",$val);
			$val = preg_replace("/\r/","",$val);
			$val = preg_replace("/,/","^",$val);
			$content_tmp .= "$val,";
		}
		$content_tmp = preg_replace("/,$/","",$content_tmp);
		$content .= $content_tmp."\r\n";
	}

	// Send the XLS data
	echo $content;
}
//========......function to get Record count from admin or member side...........==============================
function GetPageRecordCount($For = 'A')
{
	global $dbh;
	$SelectQuery = "select value from site_options where type='admreccount'";
	$Result = $dbh->query($SelectQuery);
	if(@mysql_num_rows($Result) > 0)
	{
		$Row = @mysql_fetch_object($Result);
		if($For == 'A')
			return $Row->admreccount;
		else
			return $Row->visreccount;
	}
	else
		return 5;
}

function paginationHeader($SelectQuery,$DefaultOrderBy){

	global $products;
	 $TotalCount = 10;

	 $PageRecords = 10;
	
		if(isset($_POST['PageCounter']))
			$PageCounter = $_POST['PageCounter'];
		else
			$PageCounter=0;
			
		if($_POST['orderby']=='')
			$OrderBy = $DefaultOrderBy;
		else
			$OrderBy = $_POST['orderby'];
		
		$RecordsFrom = $PageRecords * $PageCounter;
		
		$QueryCurrent = $SelectQuery." order by $OrderBy LIMIT $RecordsFrom,$PageRecords";
		
		$CurrentCatg = mysql_query($Sql);
		
		$CurrentCount = @mysql_num_rows($CurrentCatg);
		
		$CountStartFrom = $PageCounter * $PageRecords;
		
		if($TotalCount >= $RecordsFrom + $PageRecords)
			$CountUpTo = $PageCounter * $PageRecords + $PageRecords;
		else if(!($TotalCount < $RecordsFrom))
			$CountUpTo = $PageCounter * $PageRecords + ($TotalCount - $PageCounter * $PageRecords);
		
		$Total = $CountUpTo - $CountStartFrom;
		$PagValueAry = array('QueryCurrent' => $QueryCurrent,'Result' => $CurrentCatg, 'TotalCount' =>$TotalCount, 'PageRecords' =>$PageRecords,'PageCounter' => $PageCounter, 'OrderBy' => $OrderBy, 'RecordsFrom' => $RecordsFrom,'CurrentCount' => $CurrentCount, 'CountStartFrom' => $CountStartFrom,'CountUpTo' => $CountUpTo,'Total' => $Total);
		
		return $PagValueAry;
}

function displayPagination($Proid,$Caller) {

		global $PagValueAry;

		$html = "<form name='frmlist' action='' method='post'><input type=hidden name=Proid value='".$Proid."'><input type=hidden name=numrecord value=$PageRecords><input type=hidden name=PageCounter value=$PageCounter><input type=hidden value='$OrderBy' name='orderby'><input type=hidden value='$SelectQuery' name='SelectQuery'><input type=hidden value='$SearchHeading' name='SearchHeading'></form>";

	return $html;	
	}
	
function days_in_month($month="", $year="") 
{ 
	return $month == 2 ? ($year % 4 ? 28 : ($year % 100 ? 29 : ($year % 400 ? 28 : 29))) : (($month - 1) % 7 % 2 ? 30 : 31);
}	
	
?>
